﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Meraz.Core.Parsers
{
    public class FireDogLakeParser : RegexBlogParser
    {
        string dateString = null;
        string rawAliasString = null;
        List<string> aliases = new List<string>();
        const string bylinePattern = @"<td>\s*By:\s*(?<ALIASES><a .*</a>)(?<DATE>[^<]+?)\s*</td>";
        // By: <a href=""http://news.firedoglake.com/author/dday/"" title=""Posts by David Dayen"">David Dayen</a> Monday August 2, 2010 12:25 pm          </td>";
        void ParseByLine(string source)
        {
            try
            {
                Match match = Regex.Match(source, bylinePattern);
                if (match.Success)
                {
                    dateString = match.Groups["DATE"].Value;
                    rawAliasString = match.Groups["ALIASES"].Value;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("Problem parsing source using /{0}/", bylinePattern));
                Debug.WriteLine(ex);
            }
        }

        internal override List<string> ParseAliases(string source)
        {
            if (rawAliasString == null)
                ParseByLine(source);
            Debug.WriteLine(rawAliasString);
            string[] delimiters = new string[] {"and" };
            string noHtml = RemoveHtml(rawAliasString);
            return noHtml.Split(delimiters, StringSplitOptions.RemoveEmptyEntries).ToList();
        }

        internal override DateTime ParseDate(string source)
        {
            if (dateString == null)
                ParseByLine(source);
            DateTime result;
            if (!DateTime.TryParse(dateString, out result))
                result = DateTime.MinValue;
            return result;
        }

        internal override string ParseBody(string source)
        {
            string startMarker = @"<div class=""postContent"">";
            string endMarker = @"<div class=""postFooter"">";

            int start, end;
            start = source.IndexOf(startMarker);
            if (start < 0)
                throw new ApplicationException();

            start += startMarker.Length;
            end = source.IndexOf(endMarker, start);
            return source.Substring(start, end - start);
        }
    }
}
